package com.ton.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

@Configuration
public class NetContext implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {
    public static ApplicationContext applicationContext;

    @SuppressWarnings("unchecked")
    public static <T> T getInstance(Class<?> clz) {
        Object obj = applicationContext.getBean(clz);
        if (obj == null) {
            String clzName = clz.getSimpleName();
            String first = String.valueOf(clzName.charAt(0));
            clzName = first.toLowerCase() + clzName.substring(1);
            obj = applicationContext.getBean(clzName);
        }
        return (T) obj;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getInstance(String name) {
        return (T) applicationContext.getBean(name);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
}
